﻿/**
 * ...
 * @author krozalski
 */

package hapi.flash.util;

import hapi.ui.Pressable;
import hapi.event.Notifier;
import hapi.event.HapiDispatcher;

class KeyboardKey implements Pressable {
	
	public var code(default, null):Int;
	public var onPress(getOnPress, null):Notifier<PressEvent>;
	public var onRelease(getOnRelease, null):Notifier<ReleaseEvent>;
	
	var pressDispatcher:HapiDispatcher<PressEvent>;
	var releaseDispatcher:HapiDispatcher<ReleaseEvent>;
	
	var pressed:Bool;
	
	public function new(keyCode) {
		this.code = keyCode;
		this.pressDispatcher = new HapiDispatcher();
		this.releaseDispatcher = new HapiDispatcher();
		this.release();
		Keyboard.getKeyboard().registerKey( this );
	}
	
	public static function createByAscii(key:String) {
		key = key.toUpperCase();
		return new KeyboardKey(key.charCodeAt(0));
	}
	
	public function press() {
		pressed = true;
		pressDispatcher.dispatchEvent( cast { source:this } );
	}
	
	public function release() {
		pressed = false;
		releaseDispatcher.dispatchEvent( cast { source:this } );
	}
	
	public function isPressed() {
		return pressed;
	}
	
	public function isReleased() {
		return ! isPressed();
	}
	
	function getOnPress():Notifier<PressEvent> {
		return pressDispatcher;
	}
	
	function getOnRelease():Notifier<ReleaseEvent> {
		return releaseDispatcher;
	}
}